const serialize = (obj) => {
  var query='',name, value, subName, innerObj, i, p;
  for (name in obj) {
    value = obj[name];
    if (value instanceof Array) {
      for (i = 0; i < value.length; ++i) {
        if ((value[i] instanceof Object) || (value[i] instanceof Array)) {
          innerObj = {};
          innerObj[name + '[' + i + ']'] = value[i];
          (p = serialize(innerObj)) && (query += p + '&');
        } else if (value[i] !== undefined && value[i] !== null) {
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value[i]) + '&';
        }

      }
    } else if (value instanceof Object) {
      for (subName in value) {
        innerObj = {};
        innerObj[name + '.' + subName] = value[subName];
        (p = serialize(innerObj)) && (query += p + '&');
      }
    } else if (value !== undefined && value !== null) {
      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
  }
  return query.length ? query.substr(0, query.length - 1) : query;
}
const deserializeQ = (str) => {
  let arr = str == '' || decodeURIComponent(str).indexOf('?') == -1 ? [] : decodeURIComponent(str).split('?')[1].split('&'),obj={};
  arr.forEach(item=>{
    obj[item.split('=')[0]] = item.split('=')[1]
  });
  return obj;
}
const getViewRect = (selector) =>{
	return new Promise((resolve) => {
		let view = uni.createSelectorQuery().select(selector);
		view.fields({
			size: true,
			rect: true,
			scrollOffset:true
		}, (res) => {
			resolve(res);
		}).exec();
	})
}
//防止连续触发
const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}


module.exports = {
	  serialize: serialize,
	  deserializeQ: deserializeQ,
	  getViewRect:getViewRect,
	  throttle:throttle
	 
}